//数据库接口库
var util = require('util');
var db = require("./db.js");

//获取单个配置信息
//@id 主键
exports.getById = function(id, callback) {
    db.db().get("SELECT * FROM config_model WHERE id = ?", [id], callback);
}

//获取单个配置信息
//@key 键
exports.getByKey = function(key, callback) {
    db.db().get("SELECT * FROM config_model WHERE key = ?", [key], callback);
}

//获取单个配置信息
//@category 分类
//@key 键
exports.getByCategoryKey = function(category, key, callback) {
    db.db().get("SELECT * FROM config_model WHERE category = ? AND key = ?", [category,key], callback);
}

//获取单个配置信息
//@category 分类
//@key 键
//@defaultValue 默认值
exports.getByCategoryKeyOrDefault = function(category, key, defaultValue, callback) {
    db.db().get("SELECT * FROM config_model WHERE category = ? AND key = ?", [category,key], function(err, row){
        if(err || row == undefined) callback(null, {Category:category, Key:key, Value:defaultValue});
        else callback(null, row);
    });
}

//全部配置
//@pageNumber 从1开始
//@itemsPerPage 分页大小
//@category System:系统配置 User:用户配置
exports.getPagedResult = function(pageNumber, itemsPerPage, category, callback){
    util.log(' getPagedResult from config_model');
    if (pageNumber === undefined) pageNumber = 1;
    if (itemsPerPage === undefined) itemsPerPage = 20;
    if (category === undefined) category = "";

    if (category === "")
        db.db().all("SELECT * FROM config_model LIMIT ?,?", [pageNumber-1,itemsPerPage], callback);
    else
        db.db().all("SELECT * FROM config_model WHERE category=? LIMIT ?,?", [category,pageNumber-1,itemsPerPage], callback);
}

//保存或更新
//@config 配置消息\
exports.saveOrUpdate = function(config, callback){
    db.db().run("REPLACE INTO config_model(Id,Version,Key,Comment,CreatedBy,CreatedTS,ChangedBy,ChangedTS,Category,Value)VALUES (?,?,?,?,?,?,?,?,?,?)",
    [config.Id,config.Version,config.Key,config.Comment,config.CreatedBy,config.CreatedTS,config.ChangedBy,config.ChangedTS,config.Category,config.Value],
    callback)
}

//删除
//@id 主键
exports.delete = function(id, callback){
    db.db().run("DELETE FROM config_model WHERE Id = ?", [id], callback);
}
